<template>
  <view>

    <!-- <view class="flex-block">
      <view style="flex: 1;" class="tab-btn" :class="{active: activeIndex == 1}" @click="tabClick(1)">物流</view>
      <view style="flex: 1;" class="tab-btn" :class="{active: activeIndex == 0}" @click="tabClick(0)">自提</view>
    </view> -->

    <view class="u-p-20" v-if="activeIndex == 1">
      <up-form :model="model1" ref="formRef" :rules="rules" labelWidth="100px">
        <up-form-item
            label="收货地址"
            prop="addressStr"
            borderBottom
            ref="item1"
        >
          <view @click="toAddrMng()">
            <view v-if="model1.addressStr">{{ model1.addressStr }}</view>
            <view class="u-tips-color" v-else>请选择收货地址</view>
          </view>
          <template #right>
            <up-icon
                name="arrow-right"
            ></up-icon>
          </template>
        </up-form-item>
        <up-form-item
            label="预期收货时间"
            borderBottom
            ref="item1"
        >
          <view @click="selectTime">
            <view v-if="model1.expressTime.period">{{ model1.expressTime.period }}</view>
            <view v-else class="u-tips-color txt-normal">请选择</view>
          </view>
          <template #right>
            <up-icon
                name="arrow-right"
            ></up-icon>
          </template>
        </up-form-item>
        <up-form-item
            label="出库"
            prop="storeStr"
            borderBottom
            ref="item1"
        >
          <view @click="selectStock">
            <view v-if="model1.storeStr">{{ model1.storeStr }}</view>
            <view class="u-tips-color" v-else>请选择出库地址</view>
          </view>
          <template #right>
            <up-icon
                name="arrow-right"
            ></up-icon>
          </template>
        </up-form-item>
        <up-form-item
            label="物流费用"
            borderBottom
            ref="item1"
        >
          <template #right>
            <view style="text-align: right;">
              <view class="txt-small u-warning-dark">¥{{ model1.expressTime.fee }}</view>
              <view class="txt-small u-tips-color">{{ model1.expressTime.desc }}</view>
            </view>
          </template>
        </up-form-item>
      </up-form>
    </view>
    <view class="u-p-20" v-if="activeIndex == 0">
      <up-form :model="model1" ref="formRef" :rules="rules" labelWidth="100px">
        <up-form-item
            label="仓库地址"
            prop="storeStr"
            borderBottom
            ref="item1"
        >
          <view @click="selectStock">
            <up-input
                v-model="model1.storeStr"
                disabledColor="#ffffff"
                placeholder="请选择出库地址"
                border="none"
            ></up-input>
          </view>
          <template #right>
            <up-icon
                name="arrow-right"
            ></up-icon>
          </template>
        </up-form-item>
        <up-form-item
            label="预约时间"
            borderBottom
            ref="item1"
        >
          <view @click="datetimeShow = true">
            {{ model1.bookTime || '请选择预约时间' }}
          </view>
          <up-datetime-picker
              :show="datetimeShow"
              v-model="currentDate"
              mode="datetime"
              :minDate="minDate"
              :maxDate="maxDate"
              @confirm="handleDatePickerConfirm"
          ></up-datetime-picker>
        </up-form-item>

        <up-form-item
            label="预约电话"
            prop="phone"
            borderBottom
            ref="item1"
        >
          <up-input
              v-model="model1.phone"
              disabledColor="#ffffff"
              placeholder="请填写预约电话"
              border="none"
          ></up-input>
        </up-form-item>
      </up-form>
    </view>

    <view class="u-border-top">
      <view
        class="u-p-l-20 u-p-r-20 u-p-b-30 u-p-t-30 u-border-bottom"
        v-for="(item, index) in goodsInfoList" :key="index"
      >
        <goods-item
          type="cart"
          :data="item"
          size="168rpx"
          @changeNum="getGoods"
        ></goods-item>
      </view>
    </view>

    <view class="p-10 p-t-0" style="line-height: 3;">
      <view class="flex-block" style="justify-content: space-between;">
        <view class="u-tips-color">原价:</view>
        <view class="txt-deco u-tips-color">¥{{ originPrice }}</view>
      </view>
      <view class="flex-block" style="justify-content: space-between;">
        <view class="u-tips-color">折后价:</view>
        <view>¥{{ totalPrice }}</view>
      </view>
      <view class="flex-block" style="justify-content: space-between;">
        <view class="u-tips-color">运费:</view>
        <view>¥{{ model1.expressTime.fee }}</view>
      </view>
      <view class="flex-block" style="justify-content: space-between;">
        <view class="u-tips-color">合计:</view>
        <view class="u-warning-dark">¥{{ totalFee }}</view>
      </view>
    </view>

    <view class="u-p-20">
      <up-form ref="formRef" :model="formData">
        <up-form-item label="备注" prop="remark">
          <up-textarea
            v-model="formData.remark"
            placeholder="如需留言,请输入"
            showLimit
          ></up-textarea>
        </up-form-item>
      </up-form>
    </view>
  </view>
</template>

<script>
import moment from 'moment'
import { useAddrStore } from '@/stores/addr'
export default {
  data() {
    return {
      datetimeShow: false,
      currentDate: Number(new Date()),
      minDate: Number(new Date()),
      maxDate: moment().add('d', 7),
      activeIndex: 1,
      model1: {
        addressStr: '',
        address: {},
        storeStr: '',
        store: {},
        expressInfo: {},
        bookTime: '',
        expressTime: {}
      },
      rules: {
				addressStr: [
					{
						required: true,
						message: '请选择收货地址',
						trigger: ['blur', 'change']
					}
				],
				storeStr: [
					{
						required: true,
						message: '请选择出库地址',
						trigger: ['blur', 'change']
					}
				],
				phone: [
					{
						required: true,
						message: '请输入预约电话',
						trigger: ['blur', 'change']
					}
				],
			},

      goodsInfoList: [],
      formData: {},
      expressPeriodFees: [],
      storesOption: [],
      addrStore: useAddrStore()
    }
  },
  computed: {
    totalPrice() {
      let total = 0
      this.goodsInfoList.forEach(item => {
        total += item.price * item.quantity
      })
      return parseFloat(total.toFixed(2))
    },
    originPrice() {
      let total = 0
      this.goodsInfoList.forEach(item => {
        total += item.guidePrice * item.quantity
      })
      return parseFloat(total.toFixed(2))
    },
    totalFee() {
      if (!this.model1.expressTime.fee) return this.totalPrice
      const total = this.totalPrice + this.model1.expressTime.fee
      return parseFloat(total.toFixed(2))
    }
  },
  mounted() {
    this.getGoods()
    this.getExpress()
    this.getExpressInfo()
    this.getStores()
    this.getAddr()
  },
  methods: {
    tabClick(index) {
      this.activeIndex = index
    },
    async getGoods() {
      let { data } = await this.$api.cart.get()
      this.goodsInfoList = data.items || [];
    },
    getExpress() {
      this.$api.common.express().then(res => {
        if (res.code == 200) {
          this.model1.expressInfo = res.data
        }
      })
    },
    async getExpressInfo() {
      const res = await this.$api.config.expressPeriodFee()
      this.expressPeriodFees = res.data.filter(v => this.totalPrice < v.maxPrice && v.minPrice <= this.totalPrice) || []

      // 设置默认免费配送周期
      let val = this.expressPeriodFees
      .filter(v => v.fee === 0)
      val = val[0] || {}
      console.log(val)
      this.model1.expressTime = val
    },
    toAddrMng() {
      uni.navigateTo({
        url: '/pages/address/address?type=select',
        events: {
          // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
          addListenerSendAddr: (data) => {
            console.log(data)
            if (data) {
              this.model1.address = data
              this.model1.addressStr = data.address + data.num
            }
          }
        }
      })
    },
    async getAddr() {
      let {data} = await this.$api.user.address()
      this.model1.address = data[0]
      this.model1.addressStr = data[0].address + data[0].num
    },
    async getStores() {
      let { data } = await this.$api.common.store()
      this.storesOption = data.map(v => v.name)

      this.model1.store = data[0];
      this.model1.storeStr = data[0].name;
    },
    async selectStock() {
      uni.showActionSheet({
        itemList: this.storesOption,
        success: ({ tapIndex }) => {
          this.model1.store = data[tapIndex];
          this.model1.storeStr = data[tapIndex].name;
        },
        fail: (error) => {}
      })
    },
    async selectTime() {
      uni.showActionSheet({
        itemList: this.expressPeriodFees.map(v => v.period),
        success: ({ tapIndex }) => {
          this.model1.expressTime = this.expressPeriodFees[tapIndex];
        },
        fail: (error) => {}
      })
    },
    handleDatePickerConfirm(data) {
      this.model1.bookTime = moment(data.value).format('YYYY-MM-DD HH:mm');
      this.datetimeShow = false;
    }
  },
}
</script>

<style lang="stylus" scoped>
.tab-btn
  height: 90rpx
  text-align center
  line-height 90rpx
  background: #f4f4f4
  border-bottom: 1rpx solid #f4f4f4
  &.active
    background: #ffffff
</style>